package com.gamerent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gamerent.dto.UserLoginDTO;
import com.gamerent.dto.UserRegisterDTO;
import com.gamerent.entity.User;
import com.gamerent.entity.UserAccount;
import com.gamerent.mapper.UserAccountMapper;
import com.gamerent.mapper.UserMapper;
import com.gamerent.service.UserService;
import com.gamerent.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    @Transactional
    public User register(UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", registerDTO.getUsername());
        User existUser = userMapper.selectOne(wrapper);
        if (existUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建用户
        User user = new User();
        user.setUsername(registerDTO.getUsername());

        user.setPassword(registerDTO.getPassword()); // 直接存储原始密码

        user.setEmail(registerDTO.getEmail());
        user.setPhone(registerDTO.getPhone());
        user.setNickname(registerDTO.getNickname());
        user.setStatus(1); // 正常状态

        userMapper.insert(user);

        // 创建用户账户
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(user.getId());
        userAccount.setBalance(BigDecimal.ZERO);
        userAccount.setFrozenBalance(BigDecimal.ZERO);
        userAccount.setTotalRecharge(BigDecimal.ZERO);
        userAccount.setTotalConsume(BigDecimal.ZERO);
        userAccountMapper.insert(userAccount);

        return user;
    }

    @Override
    public Map<String, Object> login(UserLoginDTO loginDTO) {
        // 查找用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", loginDTO.getUsername());
        User user = userMapper.selectOne(wrapper);

        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        if (!loginDTO.getPassword().equals(user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 检查用户状态
        if (user.getStatus() == 0) {
            throw new RuntimeException("用户已被禁用");
        }

        // 生成JWT Token
        String token = jwtUtil.generateToken(user.getId(), user.getUsername());

        Map<String, Object> result = new HashMap<>();
        result.put("userId", user.getId());
        result.put("username", user.getUsername());
        result.put("token", token);
        result.put("expiresIn", 86400); // 24小时

        return result;
    }

    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public User findById(Long userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public User updateUser(User user) {
        // 不允许更新密码等敏感信息
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setNickname(user.getNickname());
        updateUser.setAvatar(user.getAvatar());
        updateUser.setGender(user.getGender());
        updateUser.setBirthday(user.getBirthday());

        userMapper.updateById(updateUser);
        return userMapper.selectById(user.getId());
    }

    @Override
    public void updateLastLogin(Long userId, String clientIp) {
        User user = new User();
        user.setId(userId);
        user.setLastLoginTime(LocalDateTime.now());
        user.setLastLoginIp(clientIp);
        userMapper.updateById(user);
    }
}